package cn.swh.guguanjia.controller;

import cn.swh.guguanjia.entity.Result;
import cn.swh.guguanjia.entity.SysResource;
import cn.swh.guguanjia.entity.SysUser;
import cn.swh.guguanjia.service.SysResourceService;
import cn.swh.guguanjia.service.SysUserService;
import cn.swh.guguanjia.util.EncryptUtils;
import com.baomidou.kaptcha.Kaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: swh
 * @Description:
 * @Date: 2020/10/23 18:43
 * @Version: 1.0
 */
@Controller
@RequestMapping("main")
public class MainController {

    @Autowired
    private Kaptcha kaptcha;

    @Autowired
    private SysUserService userService;

    @Autowired
    SysResourceService sysResourceService;

    @RequestMapping("navbar")
    public String navbar() {
        return "/common/navbar.html";
    }

    @RequestMapping("sidebar")
    public String sidebar() {
        return "/common/sidebar.html";
    }


    @RequestMapping("login")
    @ResponseBody
    public Result login(String username, String password, String code, HttpSession session){
        if(kaptcha.validate(code)){
            SysUser login = new SysUser();
            login.setUsername(username);
            login.setPassword(EncryptUtils.MD5_HEX(EncryptUtils.MD5_HEX(password)+username));
            login = userService.selectOne(login);
           //判断用户是否为空如果存在则不为null
            if(login!=null){
                //正确登录用户
                //存session
                session.setAttribute("login",login);
                //清空密码
                login.setPassword(null);

                List<SysResource> resources = sysResourceService.selectByUid(login.getId());

                session.setAttribute("resources",resources);
                HashMap<Object, Object> map = new HashMap<>();
                map.put("login",login);
                map.put("resources",resources);

                return new Result(true,"登录成功",map);
            }else {
                return new Result(false,"用户名或密码错误",null);
            }
        }
        return new Result(false,"验证码错误",null);
    }


    @RequestMapping("logout")
    @ResponseBody
    public Result logout(HttpSession session) {
        session.invalidate();
        return new Result(true,"成功退出",null);
    }


}
